import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api'

interface UserInfo {
  id: string
  username: string
  email?: string
  avatar?: string
  role: string
  createdAt: Date
  updatedAt: Date
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)
  const isLoading = ref(false)
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const username = computed(() => userInfo.value?.username || '未登录')
  const userRole = computed(() => userInfo.value?.role || 'guest')
  
  // 方法
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }
  
  const clearToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }
  
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
  }
  
  const clearUserInfo = () => {
    userInfo.value = null
  }
  
  const login = async (username: string, password: string) => {
    try {
      isLoading.value = true
      
      const response = await api.user.login({ username, password })
      
      if (response.token) {
        setToken(response.token)
        setUserInfo(response.user)
        ElMessage.success('登录成功')
        return true
      }
      
      return false
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败，请检查用户名和密码')
      return false
    } finally {
      isLoading.value = false
    }
  }
  
  const logout = async () => {
    try {
      await api.user.logout()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      clearToken()
      clearUserInfo()
      ElMessage.success('已退出登录')
    }
  }
  
  const getUserInfo = async () => {
    try {
      const response = await api.user.getInfo()
      setUserInfo(response)
      return response
    } catch (error) {
      console.error('获取用户信息失败:', error)
      clearToken()
      clearUserInfo()
      return null
    }
  }
  
  const changePassword = async (oldPassword: string, newPassword: string) => {
    try {
      await api.user.changePassword({
        oldPassword,
        newPassword
      })
      ElMessage.success('密码修改成功')
      return true
    } catch (error) {
      console.error('密码修改失败:', error)
      ElMessage.error('密码修改失败，请重试')
      return false
    }
  }
  
  // 初始化用户状态
  const initUser = async () => {
    if (token.value) {
      try {
        await getUserInfo()
      } catch (error) {
        console.error('初始化用户状态失败:', error)
        clearToken()
        clearUserInfo()
      }
    }
  }
  
  return {
    // 状态
    token,
    userInfo,
    isLoading,
    
    // 计算属性
    isLoggedIn,
    username,
    userRole,
    
    // 方法
    setToken,
    clearToken,
    setUserInfo,
    clearUserInfo,
    login,
    logout,
    getUserInfo,
    changePassword,
    initUser
  }
})